// pages/feedback/feedback.js
const feedbackService = require('../../utils/feedback');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    feedbackType: '',
    feedbackContent: '',
    contentLength: 0,
    contactInfo: '',
    canSubmit: false,
    submitting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 加载之前保存的联系方式
    const savedContact = feedbackService.getSavedContactInfo();
    this.setData({
      contactInfo: savedContact
    });
  },

  /**
   * 选择反馈类型
   */
  selectType: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      feedbackType: type
    });
    this.checkFormValidity();
  },

  /**
   * 处理内容输入
   */
  handleContentInput: function(e) {
    const content = e.detail.value;
    this.setData({
      feedbackContent: content,
      contentLength: content.length
    });
    this.checkFormValidity();
  },

  /**
   * 处理联系方式输入
   */
  handleContactInput: function(e) {
    this.setData({
      contactInfo: e.detail.value
    });
  },

  /**
   * 检查表单有效性
   */
  checkFormValidity: function() {
    const isValid = feedbackService.Validator.isValid({
      type: this.data.feedbackType,
      content: this.data.feedbackContent
    });
    
    this.setData({
      canSubmit: isValid
    });
  },

  /**
   * 提交反馈
   */
  submitFeedback: function() {
    if (this.data.submitting || !this.data.canSubmit) {
      return;
    }
    
    this.setData({
      submitting: true
    });
    
    const feedbackData = {
      type: this.data.feedbackType,
      content: this.data.feedbackContent,
      contact: this.data.contactInfo
    };
    
    feedbackService.submitFeedback(feedbackData)
      .then(res => {
        wx.showToast({
          title: '反馈提交成功',
          icon: 'success',
          duration: 2000
        });
        
        // 2秒后返回上一页
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      })
      .catch(err => {
        wx.showToast({
          title: err.message || '提交失败，请重试',
          icon: 'none',
          duration: 2000
        });
      })
      .finally(() => {
        this.setData({
          submitting: false
        });
      });
  }
}) 